/** 
* Copyright (C) 2012-2018 ZEEI Inc.All Rights Reserved.
* 项目名称：pls
* 文件名称：EnterlistGisControllerTest.java
* 包  名  称：com.zeei.pls
* 文件描述：TODO 请修改文件描述
* 创建日期：2018年1月5日下午2:02:42
* 
* 修改历史
* 1.0 jiangqingpeng 2018年1月5日下午2:02:42 创建文件
*
*/

package com.zeei.pls.controller;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

/**
 * @类型名称：BaseController
 * @类描述：TODO Controller测试基础类
 * @功能描述：TODO 请修改功能描述
 * @创建作者：YuZhending
 */
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations={"classpath:applicationContext.xml", "classpath:spring-mvc.xml","classpath:mybatis-config.xml"})
public class BaseController {

	@Autowired
	protected WebApplicationContext wac;
	
	protected MockMvc mvc;
	
	@Before
	public void setup() {
		this.mvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
	}
	
	protected RequestBuilder createRequestBuilder(String url, Map<String, Object> params) {
		MockHttpServletRequestBuilder  builder = post(url);
		Iterator<String> it = params.keySet().iterator();
		while(it.hasNext()) {
			String key = it.next();
			Object value = params.get(key);
			if(value instanceof String[]) {
				builder.param(key, (String[])value);
			} else if(value instanceof String) {
				builder.param(key, (String)value);
			} else {
				throw new UnsupportedOperationException("only type of String or String[]");
			}
		}
		
		return builder;
	}
	
	/***
	 * @param url
	 * @param params
	 */
	protected void execute(String url, Map<String, Object> params) {
		RequestBuilder builder = createRequestBuilder(url, params);
		try {
			this.mvc.perform(builder)
            .andExpect(status().isOk())  
            //.andExpect(content().contentType("application/json;charset=UTF-8"))  
            .andDo(print()); // print  
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	protected void execute(String url, String key, String... value) {
		Map<String, Object> params = new HashMap<>();
		params.put(key, value);
		
		execute(url, params);
	}
}
